var viewPosition;
var viewshed3D;
var Visualfield_handler;
var Visualfield_pointHandler;

function InitVisualfield() {
    return;
    var arrViewField = [];
    var viewModel = {
        verticalAngle: 90,
        horizontalAngle: 120,
        distance: 10
    };

    var e = new Cesium.ViewShed3D(viewer, {
        horizontalAngle: Number(viewModel.horizontalAngle),
        verticalAngle: Number(viewModel.verticalAngle),
        distance: Number(viewModel.distance),
        calback: function() {
            viewModel.distance = e.distance
        }
    });
    arrViewField.push(e);
}

function Visualfield_clear() {
    Visualfield_pointHandler.clear();
    if (Visualfield_pointHandler) {

    }
    $("#wrapper").hide();
    removeAllEntities();
    viewshed3D.distance = 0.1;
    viewer.scene.viewFlag = true;
    Visualfield_handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    Visualfield_handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK)
}

/*
 * @Author: Wang Er
 * @Date: 2020-08-06 16:43:28 
 * @Last Modified by: Wang Er
 */
/***************************
 * 视域分析模块 * 以下
 ****************************/
function createViewershed() {
    // MapStatic.flyTo({ lon: 115.77774943, lat: 40.51669238, height: 3000 });

    // 开启地形深度监测
    viewer.scene.globe.depthTestAgainstTerrain = true;

    // 设定初始视角位置点
    var viewPoint = Cesium.Cartesian3.fromDegrees(118.69559372197259, 39.74680012849921, 1000);
    var viewPointEntity = viewer.entities.add({
        position: viewPoint,
        ellipsoid: {
            radii: new Cesium.Cartesian3(5, 5, 5),
            material: Cesium.Color.YELLOW
        },
    });

    // 视角位置创建坐标轴
    var transform = Cesium.Transforms.eastNorthUpToFixedFrame(viewPoint);
    var modelMatrixPrimitive = viewer.scene.primitives.add(new Cesium.DebugModelMatrixPrimitive({
        modelMatrix: transform,
        length: 10.0
    }));

    // 世界坐标转换为投影坐标
    var webMercatorProjection = new Cesium.WebMercatorProjection(viewer.scene.globe.ellipsoid);
    var viewPointWebMercator = webMercatorProjection.project(Cesium.Cartographic.fromCartesian(viewPoint));

    // 排除碰撞监测的对象
    var objectsToExclude = [viewPointEntity, modelMatrixPrimitive];

    // 目标点集合
    var TargetPoints = [];

    // 视域点和目标点的距离
    var radius = 0;

    // 计算45°和135°之间的目标点
    for (var i = 45; i <= 135; i++) {
        var linePoints = []; //记录一条线上的所有目标点
        var pointsNum = 15; //该方向插值点数
        var lineDis = 200; //每两个插值点之间的距离m1
        for (let index = 0; index < pointsNum; index++) {
            radius = index * lineDis;
            // 度数转弧度
            var radians = Cesium.Math.toRadians(i);
            // 计算目标点
            var toPoint = new Cesium.Cartesian3(viewPointWebMercator.x + radius * Math.cos(radians), viewPointWebMercator.y + radius * Math.sin(radians), 0);
            // 投影坐标转世界坐标
            toPoint = webMercatorProjection.unproject(toPoint);
            // TargetPoints.push(Cesium.Cartographic.toCartesian(toPoint.clone()));
            var m_cartesian3 = Cesium.Cartographic.toCartesian(toPoint.clone());
            var m_ellipsoid = viewer.scene.globe.ellipsoid;
            var m_cartographic = m_ellipsoid.cartesianToCartographic(m_cartesian3);
            var m_height = viewer.scene.globe.getHeight(m_cartographic);
            var m_point = Cesium.Cartesian3.fromDegrees(m_cartographic.longitude / Math.PI * 180, m_cartographic.latitude / Math.PI * 180, m_height);
            linePoints.push({
                data: m_point,
                show: true
            });
        }
        TargetPoints.push({
            id: i,
            points: linePoints
        });
    }
    pickFromRay();

    function pickFromRay() {
        for (var i = 0; i < TargetPoints.length; i++) {
            var cur_LinePoints = TargetPoints[i].points;
            cur_LinePoints.forEach(element => {
                // 计算射线的方向，目标点left 视域点right
                var direction = Cesium.Cartesian3.normalize(Cesium.Cartesian3.subtract(element.data, viewPoint, new Cesium.Cartesian3()), new Cesium.Cartesian3());
                // 建立射线
                var ray = new Cesium.Ray(viewPoint, direction);
                // var results = viewer.scene.drillPickFromRay(ray, 10, objectsToExclude); // 计算所有的交互点，最大不超过10个
                var result = viewer.scene.pickFromRay(ray, objectsToExclude); // 计算交互点，返回第一个
                if (result && result.position) {
                    var buffer = ReturnDistance(element.data, result.position);
                    // var M_color = Cesium.Color.GREEN;
                    if (buffer > 10) {
                        // M_color = Cesium.Color.RED;
                        element.show = false;
                    }
                }

                //添加当前视域目标点可视化信息
                // viewer.entities.add({
                //     name: "aaaa" + i,
                //     position: element.data,
                //     ellipsoid: {
                //         radii: new Cesium.Cartesian3(30, 30, 30),
                //         material: M_color
                //     },
                // })
            });

        }
        drawViewshedLine(TargetPoints);
    }

    function drawViewshedLine(data) {
        for (let index = 0; index < data.length; index++) {
            const element = data[index].points;
            var startIndex = 0;
            for (let i = 0; i < element.length; i++) {
                var defaultColor = new Cesium.Color(0.1, 1, 0.1, 0.3);
                // console.log("第" + i + '个点的起点是：' + startIndex);
                const m_linestart = element[startIndex];
                var m_lineshow = m_linestart.show;
                const m_lineCurrent = element[i];
                const m_lineEnd = element[i + 1];
                if (m_lineEnd && m_lineCurrent.show != m_lineEnd.show) {
                    if (!m_lineshow) {
                        defaultColor = new Cesium.Color(1, 0.1, 0.1, 0.3);
                    }
                    viewer.entities.add({
                        polyline: {
                            positions: [m_linestart.data, m_lineEnd.data],
                            width: 2,
                            material: defaultColor,
                            clampToGround: true
                        }
                    });
                    startIndex = i + 1;
                } else if (!m_lineEnd) {
                    if (!m_lineshow) {
                        defaultColor = new Cesium.Color(1, 0.1, 0.1, 0.3);
                    }
                    viewer.entities.add({
                        polyline: {
                            positions: [m_linestart.data, m_lineCurrent.data],
                            // arcType: Cesium.ArcType.NONE,
                            width: 2,
                            material: defaultColor,
                            // depthFailMaterial: defaultColor,
                            clampToGround: true
                        }
                    });
                }

            }
        }
    }

    //空间两点距离计算函数
    function ReturnDistance(pos0, pos1) {
        var distance = 0;
        var point1cartographic = Cesium.Cartographic.fromCartesian(pos0);
        var point2cartographic = Cesium.Cartographic.fromCartesian(pos1);
        /**根据经纬度计算出距离**/
        var geodesic = new Cesium.EllipsoidGeodesic();
        geodesic.setEndPoints(point1cartographic, point2cartographic);
        var s = geodesic.surfaceDistance;
        return s.toFixed(2);
    }

    // 处理交互点
    function showIntersection(result, destPoint, viewPoint) {
        // 如果是场景模型的交互点，排除交互点是地球表面
        if (Cesium.defined(result) && Cesium.defined(result.object)) {
            drawLine(result.position, viewPoint, Cesium.Color.GREEN); // 可视区域
            drawLine(result.position, destPoint, Cesium.Color.RED); // 不可视区域
        } else {
            drawLine(viewPoint, destPoint, Cesium.Color.GREEN);
        }
    }
}
/***************************
 * 视域分析模块 * 以上
 ****************************/